<?php
namespace app\farm\model;

use app\BaseModel;
use app\massage\model\GoodsSpe;
use app\shop\model\GoodsSpePrice;
use app\shop\model\IntegralGoods;
use app\shop\model\SeckillGoods;
use app\shop\model\StoreGoods;
use think\facade\Db;

class ShopGoods extends BaseModel
{
    //定义表名
    protected $name = 'lbfarm_shop_goods';


    protected $append = [

        'show_price',

        'show_init_price',

        'all_stock',

        'all_sale_count',

    ];


    /**
     * @param $value
     * @param $data
     * @功能说明:获取分类
     * @author chenniang
     * @DataTime: 2022-07-13 17:28
     */
    public function getCateIdAttr($value,$data){

        if(!empty($data['id'])){

            $goods_cate_model = new GoodsCate();

            $dis = [

                'a.type' => 1,

                'a.goods_id' => $data['id'],

                'b.status' => 1
            ];

            $list = $goods_cate_model->alias('a')
                    ->join('lbfarm_shop_goods_cate b','a.cate_id = b.id')
                    ->where($dis)
                    ->column('b.id');

            return array_values($list);

        }

    }



    /**
     * @param $value
     * @param $data
     * @功能说明:获取分类
     * @author chenniang
     * @DataTime: 2022-07-13 17:28
     */
    public function getStoreAttr($value,$data){

        if(!empty($data['id'])){

            $store_model = new StoreGoods();

            $dis = [

                'a.type' => 1,

                'a.goods_id' => $data['id'],

                'b.status' => 2,

                'b.type' => 2,
            ];

            $list = $store_model->alias('a')
                ->join('lbfarm_farmer b','a.store_id = b.id')
                ->where($dis)
                ->column('b.id');

            return array_values($list);

        }

    }



//    public function getTextAttr($value,$data){
//
//        if(!empty($value)){
//
//            return @unserialize($value);
//        }
//
//    }



    /**
     * @author chenniang
     * @DataTime: 2021-11-02 14:08
     * @功能说明:虚拟销量+真实销量
     */
    public function getAllSaleCountAttr($value,$data){

        if(isset($data['sale_num'])&&isset($data['true_sale_num'])){

            return $data['sale_num']+$data['true_sale_num'];

        }

    }




    /**
     * @param $value
     * @param $data
     * @功能说明:
     * @author chenniang
     * @DataTime: 2021-03-23 11:12
     */
    public function getImgsAttr($value,$data){

        if(!empty($value)){

            return explode(',',$value);

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 15:13
     * @功能说明:获取商品的最低价格
     */
    public function getShowPriceAttr($value,$data){

        if(!empty($data['id'])){

            $spe_model = new GoodsSpePrice();

            $list = $spe_model->where(['goods_id'=>$data['id']])->min('price');

            return $list;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 15:13
     * @功能说明:获取商品的最低价格
     */
    public function getShowInitPriceAttr($value,$data){

        if(!empty($data['id'])){

            $spe_model = new GoodsSpePrice();

            $list = $spe_model->where(['goods_id'=>$data['id']])->order('price,id desc')->value('original_price');

            return $list;

        }

    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-23 15:13
     * @功能说明:获取总库存
     */
    public function getAllStockAttr($value,$data){

        if(!empty($data['id'])){

            $spe_model = new GoodsSpePrice();

            $list = $spe_model->where(['goods_id'=>$data['id']])->sum('stock');

            return $list;

        }

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $cate_id = $data['cate_id'];

        unset($data['cate_id']);

        $store = $data['store'];

        unset($data['store']);

        unset($data['specsItem']);

        unset($data['specsTable']);

        $data['imgs'] = implode(',',$data['imgs']);

        $res = $this->insert($data);

        $id  = $this->getLastInsID();

        $this->updateSome($id,$data['uniacid'],$store,$cate_id);

        return $id;

    }


    /**
     * @param $id
     * @param $uniacid
     * @param $spe
     * @功能说明:
     * @author chenniang
     * @DataTime: 2021-03-23 13:35
     */
    public function updateSome($id,$uniacid,$store,$cate){

        $store_model = new StoreGoods();

        $goods_cate_model = new GoodsCate();

        $store_model->where(['type'=>1,'goods_id'=>$id])->delete();

        $goods_cate_model->where(['type'=>1,'goods_id'=>$id])->delete();

        if(!empty($store)){

            foreach ($store as $ks=>$vs){

                $insert[$ks] = [

                    'goods_id' => $id,

                    'uniacid'  => $uniacid,

                    'store_id' => $vs
                ];

            }

            $store_model->saveAll($insert);
        }

        if(!empty($cate)){

            foreach ($cate as $ks=>$vs){

                $inserts[$ks] = [

                    'goods_id' => $id,

                    'uniacid'  => $uniacid,

                    'cate_id' => $vs
                ];

            }

            $goods_cate_model->saveAll($inserts);
        }



    }






    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function goodsUpdate($dis,$data){

        $cate_id = $data['cate_id'];

        unset($data['cate_id']);

        $store = $data['store'];

        unset($data['store']);

        unset($data['specsItem']);

        unset($data['specsTable']);

        $data['imgs'] = implode(',',$data['imgs']);

        $res = $this->where($dis)->update($data);

        $this->updateSome($dis['id'],$data['uniacid'],$store,$cate_id);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-03-04 11:44
     * @功能说明:
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-13 17:03
     * @功能说明:商城列表
     */
    public function goodsList($dis,$page=10){

        $data = $this->alias('a')
                ->join('lbfarm_v2_goods_store b','a.id = b.goods_id AND b.type=1','left')
                ->join('lbfarm_v2_goods_cate c','a.id = c.goods_id AND c.type=1','left')
                ->where($dis)
                ->field('a.*')
                ->group('a.id')
                ->order('a.top desc,a.id desc')
                ->paginate($page)
                ->toArray();

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-13 17:03
     * @功能说明:商城列表
     */
    public function indexGoodsList($dis,$page=10){

        $data = $this->alias('a')
            ->join('lbfarm_v2_goods_store b','a.id = b.goods_id AND b.type=1')
            ->join('lbfarm_v2_goods_cate c','a.id = c.goods_id AND c.type=1')
            ->join('lbfarm_farmer d','b.store_id = d.id')
            ->where($dis)
            ->field('a.*,d.title as store_name,d.id as store_id,d.cover as store_cover')
            ->group('a.id')
            ->order('a.top desc,a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;
    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 16:08
     * @功能说明:开启默认
     */
    public function updateOne($id){

        $user_id = $this->where(['id'=>$id])->value('user_id');

        $res = $this->where(['user_id'=>$user_id])->where('id','<>',$id)->update(['status'=>0]);

        return $res;
    }




    /**
     * @author chenniang
     * @DataTime: 2021-03-18 10:07
     * @功能说明:增加|减少库存 增加|减少销量
     */
    public function setOrDelStock($goods_id,$spe_id,$num,$type=1,$refund = 0,$integral_id=0,$kill_atv_id=0){

        if(empty($goods_id)){

            return true;
        }

        $spe_model = new GoodsSpePrice();

        $goods_info = $this->dataInfo(['id'=>$goods_id]);

        $spe_info   = $spe_model->dataInfo(['id'=>$spe_id]);
        //退货
        if($type==1){

            $update = [

                'true_sale_num' => $goods_info['true_sale_num']-$num,

                'lock'       => $goods_info['lock']+1,

            ];
            //如果是售后增加退款数量
            if($refund==1){

                $update['refund_num'] = $goods_info['refund_num']+$num;
            }
            //减销量 加退款数量
            $res = $this->where(['id'=>$goods_id,'lock'=>$goods_info['lock']])->update($update);

            if($res!=1){

                return ['code'=>500,'msg'=>'提交失败'];
            }

            //增加库存
            $res = $spe_model->where(['id'=>$spe_id,'lock'=>$spe_info['lock']])->update(['stock'=>$spe_info['stock']+$num,'lock'=>$goods_info['lock']+1]);

            if($res!=1){

                return ['code'=>500,'msg'=>'提交失败'];
            }
            //积分
            if(!empty($integral_id)){

                $integral_goods_model = new IntegralGoods();

                $integral_goods_model->updateAtvStock($integral_id,$goods_id,$spe_id,$num,2);

            }
            //秒杀商品
            if(!empty($kill_atv_id)){

                $kill_model = new SeckillGoods();

                $kill_model->updateAtvStock($kill_atv_id,$goods_id,$spe_id,$num,2);
            }


        }else{
            //增加销量
            $res = $this->where(['id'=>$goods_id,'lock'=>$goods_info['lock']])->update(['true_sale_num'=>$goods_info['true_sale_num']+$num,'lock'=>$goods_info['lock']+1]);

            if($res!=1){

                return ['code'=>500,'msg'=>'提交失败'];
            }

            $now_stock = $spe_info['stock'] - $num;

            if($now_stock<0){

                return ['code'=>500,'msg'=>'库存不足'.$goods_info['goods_name']];

            }
            //减少库存
            $res = $spe_model->where(['id'=>$spe_id,'lock'=>$spe_info['lock']])->update(['stock'=>$spe_info['stock']-$num,'lock'=>$goods_info['lock']+1]);

            if($res!=1){

                return ['code'=>500,'msg'=>'提交失败'];
            }
            //积分
            if(!empty($integral_id)){

                $integral_goods_model = new IntegralGoods();

                $res = $integral_goods_model->updateAtvStock($integral_id,$goods_id,$spe_id,$num);

                if(!empty($res['code'])){

                    return $res;
                }

            }
            //秒杀商品
            if(!empty($kill_atv_id)){

                $kill_model = new SeckillGoods();

                $res = $kill_model->updateAtvStock($kill_atv_id,$goods_id,$spe_id,$num,1);

                if(!empty($res['code'])){

                    return $res;
                }

            }

        }

        return true;
    }



    /**
     * @author chenniang
     * @DataTime: 2020-08-25 17:19
     * @功能说明:
     */
    public function saleIngCount($uniacid,$type=1){

        $spe_price_model = new GoodsSpePrice();

        $dis  = [];

        $dis[]= ['uniacid','=',$uniacid];

        $sale_type      = $type==2?0:1;

        $sale_out_goods = $spe_price_model->getSellOut($uniacid,$sale_type);

        switch ($type){

            case 1:
                $dis[] = ['status','=',1];
                break;

            case 2:

                $dis[] = ['status','>',-1];
                break;

            case 3:
                $dis[] = ['status','=',0];
                break;

        }

        $dis[] = ['id','in',$sale_out_goods];

        $data = $this->where($dis)->count();

        return $data;
    }




}